package com.heima.article.service.impl;


import com.alibaba.fastjson.JSON;
import com.heima.article.service.ApArticleElasticSearchService;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.search.dtos.SearchArticleVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
public class ApArticleElasticSearchServiceImpl implements ApArticleElasticSearchService {
    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * 保存文章到ES索引库中
     * @param apArticle
     * @param content
     */
    @Override
    public void saveArticleToElasticSearch(ApArticle apArticle, String content) {
        //1.参数校验
        if (apArticle.getId() == null || StringUtils.isEmpty(content) || StringUtils.isEmpty(apArticle.getTitle())){
            return;
        }

        //2.封装数据
        SearchArticleVo searchArticleVo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle,searchArticleVo);
        searchArticleVo.setContent(content);

        //3.发送消息到kafka
        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(searchArticleVo));
    }
}
